package com.fanrenqiji.modules.sys.service.impl;

import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.service.BaseCommonService;
import com.fanrenqiji.modules.sys.dao.DictDao;
import com.fanrenqiji.modules.sys.entity.Dict;
import com.fanrenqiji.modules.sys.service.DictService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月6日 下午2:26:29
 * @description 数据字典业务实现类
 */
@Service(value = "dictService")
@Transactional(readOnly = true)
public class DictCommonServiceImpl extends BaseCommonService implements DictService {

	@Autowired
	private DictDao dictDao;

	/**
	 * 通过id获得字典值
	 */
	@Override
	public Dict findOne(Long id) {
		return dictDao.findOne(id);
	}

	/**
	 * 获得有效的字典分类
	 */
	@Override
	public List<String> findTypeList() {
		return dictDao.findTypeList();
	}

	@Override
	public List<Dict> findAllList() {
		return dictDao.findAllList();
	}

	/**
	 * 获得字典的分页 
	 */
	@Override
	public Page<Dict> find(Page<Dict> page, Dict dict) {
		DetachedCriteria dc = dictDao.createDetachedCriteria();
		if (StringUtils.isNotEmpty(dict.getType())) {
			dc.add(Restrictions.eq("type", dict.getType()));
		}
		if (StringUtils.isNotEmpty(dict.getDescription())) {
			dc.add(Restrictions.like("description", "%" + dict.getDescription()+ "%"));
		}
		dc.add(Restrictions.eq(Dict.DEL_FLAG, Dict.DEL_FLAG_NORMAL));
		//根据 type sort 和id排序
		dc.addOrder(Order.asc("type")).addOrder(Order.asc("sort"))
				.addOrder(Order.desc("id"));
		return dictDao.find(page, dc);
	}

	/**
	 * 保存或更新字典
	 */
	@Override
	@Transactional(readOnly = false)
	public void save(Dict dict) {
		dictDao.save(dict);
	}

}
